package com.tdd.zkconfig.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.tdd.zkconfig.listener.DataSourceChangeListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

/**
 * @author tudedong
 * @description
 * @date 2020-06-14 15:04:28
 */
public class DruidUtils {

    private DruidUtils(){
    }

    private static DruidDataSource druidDataSource;


    public static DruidDataSource getDruidDataSource() {
        return druidDataSource;
    }

    public static void setDruidDataSource(DruidDataSource druidDataSource) {
        DruidUtils.druidDataSource = druidDataSource;
    }

    public static DruidDataSource getInstance() {
        if (druidDataSource == null){
            druidDataSource = new DruidDataSource();
            ZkClient zkClient = ZkClientUtils.getZkClient();
            String url = zkClient.readData("/zookeeper/sql-url");
            String driverClassName = zkClient.readData("/zookeeper/sql-driver");
            String userName = zkClient.readData("/zookeeper/sql-username");
            String pwd = zkClient.readData("/zookeeper/sql-password");

            druidDataSource.setDriverClassName(driverClassName);
            druidDataSource.setUrl(url);
            druidDataSource.setUsername(userName);
            druidDataSource.setPassword(pwd);

            //注册监听
            zkClient.subscribeDataChanges("/zookeeper/sql-url", new DataSourceChangeListener());
            zkClient.subscribeDataChanges("/zookeeper/sql-username", new DataSourceChangeListener());
            zkClient.subscribeDataChanges("/zookeeper/sql-password", new DataSourceChangeListener());
        }

        return druidDataSource;
    }
}
